package db;

import model.Bag;
import org.apache.log4j.Logger;

import java.sql.ResultSet;
import java.util.ArrayList;

public class BagDAO {
    dbconnection dbconnection;
    java.sql.Connection myConnection;
    java.sql.Statement st;
    ResultSet rs;
    String sql = "";
    private static Logger logger = Logger.getLogger(BagDAO.class);

    public ArrayList<Bag> findAll() {
        ArrayList<Bag> bg = new ArrayList<Bag>();

        try {
            dbconnection = new dbconnection();
            myConnection = dbconnection.getConnection();
            st = myConnection.createStatement();
            sql = "SELECT * FROM bag ORDER BY id ASC";
            rs = st.executeQuery(sql);
            while (rs.next()) {
                bg.add(new Bag(rs.getInt("id"), rs.getString("type"), rs.getInt("price")));
            }
        } catch (Exception e) {
            logger.info("Could not connect to database.");
        }
        return bg;
    }

    public Bag findById(int id) {
        Bag bg = new Bag(0, null, 0);
        try {
            dbconnection = new dbconnection();
            myConnection = dbconnection.getConnection();
            st = myConnection.createStatement();
            sql = "SELECT * FROM bag WHERE id = " + id;
            rs = st.executeQuery(sql);
            while (rs.next()) {
                bg.setType(rs.getString("type"));
                bg.setId(Integer.parseInt(rs.getString("id")));
                bg.setPrice(Integer.parseInt(rs.getString("price")));
            }
            myConnection.close();
        } catch (Exception e) {
            logger.info("Unable to connect to database.");
        }

        return (bg.getType() == null || bg.getType().equals("")) ? null : bg;
    }

    public void update(Bag b) {
        try {
            dbconnection = new dbconnection();
            myConnection = dbconnection.getConnection();
            st = myConnection.createStatement();
            sql = "UPDATE bag SET type = '" + b.getType() + "', price = '" + Integer.parseInt(b.getStringPrice()) + "' WHERE id = " + b.getId();
            rs = st.executeQuery(sql);
            myConnection.close();
        } catch (Exception e) {
        }
    }
}
